/**
 */
package com.telpoo.frame.net;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.telpoo.frame.utils.Cons.NetConfig;
import com.telpoo.frame.utils.FileSupport;
import com.telpoo.frame.utils.Mlog;

/**
 * 
 * @author NAQ
 * 
 */
public class BaseNetSupport implements NetConfig {
	protected static String TAG = BaseNetSupport.class.getSimpleName();

	public  class NetData {
		public NetData() {
			
		}
		public boolean code;
		public String msg;
		public int pages;
		
		public ArrayList<?> data;
	}

	private static HttpClient myHttpClient() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
		HttpClient client = new DefaultHttpClient(params);
		return client;
	}
/*
	protected static NetData ParseJson(String jsonContent, String keys[]) {
		NetData netData = new NetData();
		if (jsonContent == null) {
			netData.code = false;
			netData.msg = HomeActivity.str_connect_error;
			return netData;
		}
		JSONObject jsonObject;
		JSONArray jsonListData;
		ArrayList<BaseObject> baseObjects = new ArrayList<BaseObject>();

		try {
			jsonObject = new JSONObject(jsonContent);
			netData.code = jsonObject.getBoolean(CODE);
			netData.msg = jsonObject.getString(SERROR);
			jsonListData = jsonObject.getJSONArray(RESULT);

			for (int i = 0; i < jsonListData.length(); i++) {
				JSONObject oneObject = jsonListData.getJSONObject(i);
				BaseObject baseObject = new BaseObject();
				for (String key : keys) {
					if (oneObject.has(key))
						baseObject.set(key, oneObject.getString(key));
					else
						Mlog.w("ParseJson=0192321= no key:" + key);
				}

				// get data in flags,
				try {
					JSONArray jarjoin_status = new JSONArray(netData.flags);
					JSONObject jojjoin_status = jarjoin_status.getJSONObject(0);
					if (jojjoin_status.has(BaseObject.JOIN_STATUS)) // get
																	// join_status
						baseObject.set(BaseObject.JOIN_STATUS, jojjoin_status.getString(BaseObject.JOIN_STATUS));

				} catch (Exception e) {
					Mlog.w("ParseJson- get other key: " + e);
				}

				baseObjects.add(baseObject);

			}
			netData.data = baseObjects;

		} catch (JSONException e) {
			netData.code = false;
			netData.msg = HomeActivity.str_connect_error;
			e.printStackTrace();
		}

		return netData;
	}*/

	public static String method_GET(String url, List<String> value) {

		int retryCount = 0;
		do {
			try {
				URL myUrl;
				if (value != null) {

					String query = "";
					for (String mstring : value) {
						query += mstring + "/";
					}
					myUrl = new URL(url + query);
				} else {
					myUrl = new URL(url);
				}
				Mlog.D(TAG + "- method_GET -URl:" + myUrl);

				HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
				conn.setConnectTimeout(CONNECTION_TIMEOUT);
				conn.setReadTimeout(SO_TIMEOUT);
				if (AUTHORIZATION_TYPE != null)
					conn.setRequestProperty("Authorization", AUTHORIZATION_TYPE);

				conn.setRequestProperty("Content-Type", CONTENT_TYPE);

				String jsonContent = FileSupport.readFromInputStream(conn.getInputStream());
				Mlog.D(TAG + "- method_GET - json result=" + jsonContent);

				conn.disconnect();
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Mlog.E(TAG + "658345234 NetworkSupport - getNetworkData - FileNotFoundException = " + ex.getMessage());

			} catch (Exception ex) {
				Mlog.E(TAG + "789345564 NetworkSupport - getNetworkData - Exception = " + ex.getMessage());
			}
		} while (++retryCount < NUMBER_OF_RETRY);

		return null;
	}

	public static String method_POST(String url, String bodySend) {

		int retryCount = 0;

		do {
			try {

				URL myUrl = new URL(url);
				HttpClient client = myHttpClient();

				HttpConnectionParams.setConnectionTimeout(client.getParams(), CONNECTION_TIMEOUT);
				HttpResponse response;

				InputStream in = null;
				try {
					HttpPost post = new HttpPost(myUrl.toURI());

					StringEntity se = new StringEntity(bodySend, "UTF8");
					Mlog.D(TAG + "-method_POST - url=" + myUrl);
					Mlog.D(TAG + "-method_POST - json sent=" + bodySend);

					se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
					se.setContentType(new BasicHeader("Authorization", AUTHORIZATION_TYPE));
					se.setContentEncoding(HTTP.UTF_8);

					post.setEntity(se);
					response = client.execute(post);

					/* Checking response */
					if (response != null) {
						in = response.getEntity().getContent(); // Get the data
					}

				} catch (Exception e) {
					Mlog.E(TAG + "576237 method_POST " + e.toString());
					return null;
				}
				String jsonContent = FileSupport.readFromInputStream(in);
				Mlog.D("method_POST - response: " + jsonContent);
				return jsonContent;
			} catch (FileNotFoundException ex) {
				Mlog.E("method_POST - getNetworkData - FileNotFoundException = " + ex.getMessage());
				return null;

			} catch (Exception ex) {
				Mlog.E("method_POST - getNetworkData - Exception = " + ex.getMessage());
				return null;
			}
		} while (++retryCount < NUMBER_OF_RETRY);

	}



	/*protected static NetData parseResponseToNetData(String response, String[] keys) {
		NetData netData = new NetData();
		if (response == null || response.length() == 0) {
			netData.code = false;
			netData.msg = HomeActivity.str_connect_error;

			return netData;
		}
		return BaseNetSupport.ParseJson(response, keys);

	}*/
	
	public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }

        }
        return false;
	}



}
